package com.daily.pump.app;

import android.Manifest;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.multidex.MultiDexApplication;

import com.daily.pump.R;
import com.daily.pump.activity.SplashActivity;
import com.daily.pump.constants.Config;
import com.daily.pump.dao.DaoSharedPreferences;
import com.daily.pump.model.Device;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.xunxi.mimi.utils.CrashHandler;
import com.xunxi.mimi.utils.LogUtil;
import com.xunxi.mimi.utils.SDCardUtil;

import java.io.File;

/**
 * 作者: liyu on  2017/11/15 0015 13:58
 * 邮箱：liyu@szy.cn
 * 功能描述:
 * 备注:
 */
public class App extends MultiDexApplication implements CrashHandler.UncaughtExceptionHanlderListener {

    private static App mInstance;

    private Device mLoginDevice;

    public static App getInstance() {
        synchronized (App.class) {
            if (mInstance == null) {
                mInstance = new App();
            }
        }
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mInstance = this;
        initLog();//日志
        initSmartRefresh();
    }

    private void initLog() {
        LogUtil.init(Config.PRINT_LOG);
        CrashHandler.getInstance(this).setHanlderListener(this);
        CrashHandler.getInstance(this).setCrashLogDir(getCrashLogDir());//设置记录错误日志目录
    }

    private void initSmartRefresh() {
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                ClassicsFooter footView = new ClassicsFooter(App.this);
                footView.setTextSizeTitle(14);
                footView.setAccentColorId(R.color.color_999999);
                return footView;
            }
        });
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                MaterialHeader materialHeader = new MaterialHeader(App.this);
                materialHeader.setColorSchemeColors(getResources().getColor(R.color.color_fd5253));
                return materialHeader;
            }
        });
    }

    /**
     * Desc:获取登录设备
     * <p>
     * Author: [李豫]
     * Date: 2020-11-12
     *
     * @return device
     */
    public Device getLoginDevice() {
        if (mLoginDevice == null) {
            mLoginDevice = DaoSharedPreferences.getInstance().getLoginDevice();
        }
        return mLoginDevice;
    }

    /**
     * Desc:设置登录设备
     * <p>
     * Author: [李豫]
     * Date: 2020-11-13
     *
     * @param loginDevice
     */
    public void setLoginDevice(Device loginDevice) {
        this.mLoginDevice = loginDevice;
        DaoSharedPreferences.getInstance().setDevice(loginDevice);
    }

    /**
     * Desc:修改登录设备
     * <p>
     * Author: [李豫]
     * Date: 2020-11-13
     *
     * @param device
     */
    public void modifyLoginDevice(Device modifyDevice, Device device) {
        DaoSharedPreferences.getInstance().deleteDevice(modifyDevice);
        mLoginDevice.deviceName = device.deviceName;
        mLoginDevice.wifiBean = device.wifiBean;
        mLoginDevice.loginName = device.loginName;
        mLoginDevice.password = device.password;
        DaoSharedPreferences.getInstance().setDevice(mLoginDevice);
    }

    public void exitLogin() {
    }

    public void exit() {
        mLoginDevice = null;
        mInstance = null;
    }

    // 获取设备ID
    public String getDeviceId() {
        String deviceId = null;
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        if (tm != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return String.valueOf(System.currentTimeMillis());
            }
            deviceId = tm.getDeviceId();
        }
        if (TextUtils.isEmpty(deviceId)) {
            deviceId = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);
        }
        return deviceId;
    }

    protected String getCrashLogDir() {
        StringBuffer sb = new StringBuffer();

        if (getRootDir() != null) {
            sb.append(getRootDir());
            sb.append(File.separator);
        } else {
            sb.append(File.separator);
            sb.append("sdcard");
            sb.append(getPackageName());
            sb.append(File.separator);
        }

        sb.append("log");

        return sb.toString();
    }

    protected String getRootDir() {
        if (SDCardUtil.isSDCardAvaiable()) {
            StringBuffer sb = new StringBuffer();
            sb.append(Environment.getExternalStorageDirectory().getPath());
            sb.append(File.separator);
            sb.append(getPackageName());

            return sb.toString();
        }

        return null;
    }

    @Override
    public void handlerUncaughtException(Thread thread, Throwable ex) {
        if (!Config.DEBUG) {
            AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(this, SplashActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            PendingIntent restartIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 500, restartIntent); // 0.5秒钟后重启应用
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }
}
